@file:OptIn(ExperimentalNativeApi::class)

package kotlinx.coroutines

import kotlin.coroutines.*
import kotlin.experimental.*
import kotlin.native.*

private const val MAX_DELAY = Long.MAX_VALUE / 2

internal actual fun createMainDispatcher(default: CoroutineDispatcher): MainCoroutineDispatcher =
    OhosMainCoroutineDispatcher(false)

internal actual fun createDefaultDispatcher(): CoroutineDispatcher = DefaultDispatcher

private object DefaultDispatcher : CoroutineDispatcher() {
    @OptIn(ExperimentalNativeApi::class)
    private val ctx = newFixedThreadPoolContext(
        Platform.getAvailableProcessors().coerceAtLeast(2),
        "Dispatchers.Default"
    )

    override fun dispatch(context: CoroutineContext, block: Runnable) {
        ctx.dispatch(context, block)
    }
}

@OptIn(InternalCoroutinesApi::class)
private class OhosMainCoroutineDispatcher(
    private val invokeImmediately: Boolean
) : MainCoroutineDispatcher() {
    override val immediate: MainCoroutineDispatcher = if (invokeImmediately) this else OhosMainCoroutineDispatcher(true)

    override fun dispatch(context: CoroutineContext, block: Runnable) {
        runOnMainThread(invokeImmediately){
            block.run()
        }
    }

    override fun isDispatchNeeded(context: CoroutineContext): Boolean {
        return !(invokeImmediately && isMainThread())
    }

}

internal actual inline fun platformAutoreleasePool(crossinline block: () -> Unit) = block()
